package com.ls.lserp.modules.produce.web;


import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.ls.lserp.modules.sys.utils.SystemMessageUtils;
import org.apache.commons.collections.map.HashedMap;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.support.RequestContext;

import com.ls.lserp.common.config.Global;
import com.ls.lserp.common.persistence.AjaxDone;
import com.ls.lserp.common.persistence.BaseEntity;
import com.ls.lserp.common.persistence.Page;
import com.ls.lserp.common.utils.ResourcesUtil;
import com.ls.lserp.common.utils.StringUtils;
import com.ls.lserp.common.web.BaseController;

import com.ls.lserp.modules.produce.entity.ProductionLocation;
import com.ls.lserp.modules.produce.service.ProductionLocationService;
import freemarker.template.Configuration;
import groovy.util.ResourceException;



@Controller
@RequestMapping(value = "${adminPath}/production/location/")
public class ProductionLocationController extends BaseController {

	
	@Autowired
	private ProductionLocationService productionLocationService;
	@Autowired
	Configuration freemarkerConfiguration;
	
	@ModelAttribute
	public ProductionLocation get(@RequestParam(required = false) String id) {

		// 判断id是否为空
		if (StringUtils.isNotBlank(id)) {
			// 执行查询语句 查询基本信息
			return productionLocationService.get(Long.parseLong(id));
		} else {

			// 若为空，实例化
			return new ProductionLocation();
		}
	}
	
	/**
	 * 生产参数一览画面
	 * 
	 * 
	 * @return
	 */
	@RequestMapping(value = { "" })
	public String produceParameter(Model model) {

		return "modules/produce/productionLocation";

	}
	
	/**
	 * @Title: 画面检索
	 * @Description: 查询页面
	 * @param produceparameter
	 * @param request
	 * @param response
	 * @param model
	 * @return searchList
	 * @throws Exception
	 */
	@RequiresPermissions("production:location:view")
	@RequestMapping(value = { "searchList" })
	@ResponseBody
	public String searchList(ProductionLocation productionLocation, HttpServletRequest request, HttpServletResponse response,
			Model model) throws Exception {
		Map<Object, Object> listMap = new HashMap<Object, Object>();
		// ajax回调时使用的一览list名
		request.setAttribute(Global.LIST_NAME, "productionLocation");

		// 画面取得的检索项目
		// 款式类别
		String styleCategoryCD = productionLocation.getStyleCategoryCD();
		// 工位名
		String itemNameCn = productionLocation.getItemNameCn();

		String strUri = request.getContextPath() + Global.getAdminPath();
		// 拼接字符串供分页使用
		String searchParam = "&itemNameCn=" + itemNameCn + "&styleCategoryCD=" + styleCategoryCD;
		// 放到Attribute里，使用Global类里面的SEARCH_PAEAM作为key
		request.setAttribute(Global.SEARCH_PAEAM, searchParam);

		// 查询一览页面数据
		Page<ProductionLocation> page = productionLocationService.findList(new Page<ProductionLocation>(request, response), productionLocation);
		
		// 读取系统路径
		// 读取文件生成字符串
		String strHtml = "";
		Map<String, Object> map = new HashedMap();
		map.put("adminUri", strUri);
		map.put("productionLocations", page.getList());
		map.put("pageNo", page.getPageNo());
		map.put("pageSize", page.getPageSize());
		map.put("springMacroRequestContext", new RequestContext (request));
		strHtml = FreeMarkerTemplateUtils
				.processTemplateIntoString(freemarkerConfiguration.getTemplate("productionLocation.ftl"), map);
		listMap.put("productionLocation", strHtml);
		listMap.put("page", page.getHtml());

			// ajax返回结果
			return renderString(response, listMap);
		}
	
	/**
	 * 进入编辑页面
	 *
	 * @return
	 */
	@RequiresPermissions("production:location:edit")
	@RequestMapping(value = "form")
	public String form() {
		// 返回页面地址
		return "modules/produce/productionLocationCreate";
	}
	
	/**
	 * 创建编辑保存仓库信息
	 * 
	 * @return
	 * @throws ParseException
	 * @throws ResourceException
	 */
	@RequiresPermissions("production:location:edit")
	@RequestMapping(value = "save")
	@ResponseBody
	public String save(ProductionLocation productionLocation, HttpServletResponse response) throws ResourceException {
		
		// 判断id是否为null （判断新建或修改）
		if(productionLocation.getId()!=null){
			// 编辑数据
			// 判断数据是否删除
			ProductionLocation ProductionLocationNew = get(productionLocation.getId().toString());
			// 判断数据是否删除
            if(ProductionLocationNew==null || BaseEntity.DEL_FLAG_DELETE.equals(ProductionLocationNew.getDeleteFlag())){
            	// 返回提示信息
            	return renderString(response,AjaxDone.error(getText("warehouse_edit_save_msg_fail")));
            }
			
            // 排他处理
		    if(productionLocation.getVersion()==get(productionLocation.getId().toString()).getVersion()){
		    	
		    	// 版本号加1
		    	productionLocation.setVersion(productionLocation.getVersion()+1);
		    }else{
		    	
		    	// 返回提示信息
		    	return renderString(response,AjaxDone.error(getText("warehouse_edit_save_msg_fail")));
		    }
		}
			
			
		    // 保存数据
			productionLocationService.saveproductionLocation(productionLocation);
			
			// 保存成功返回提示信息
			return renderString(response, AjaxDone.ok(SystemMessageUtils.getMessageName ("warehouse_edit_save_msg_success")));
	}
	
	/**
	 * 进入查看页面
	 * 
	 * @param productionLocation
	 * @param model
	 * @return
	 */
	@RequiresPermissions("production:location:view")
	@RequestMapping(value = "show")
	public String show(ProductionLocation productionLocation, Model model) {

		model.addAttribute("productionLocation", productionLocation);
		// 返回页面地址
		return "modules/produce/productionLocationShow";
	}
	
	/**
	 * 删除信息
	 * 
	 * @param productionLocation
	 * @param response
	 * @return
	 */
	@RequiresPermissions("production:location:edit")
	@RequestMapping(value = "delete")
	public String delete(ProductionLocation productionLocation, HttpServletResponse response) {

		try {

			// 执行逻辑删除方法
			productionLocationService.deleteProduce(productionLocation);
		} catch (Exception e) {
			// 记录日志
			logger.error(e.getMessage(), e);
			// 提示错误信息
			return renderString(response, AjaxDone.error(getText("System_error_please_contact_your_administrator")));
		}
		// 提示删除成功信息
		return renderString(response, AjaxDone.ok(getText("dict_delete_success")));
	}
	
	
	
	
}
